package com.dikeleakagedetection.myapplication.utils

import android.graphics.Bitmap
import android.graphics.Bitmap.CompressFormat
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.media.ExifInterface
import android.net.Uri

import com.dikeleakagedetection.myapplication.DikeLeakageDetectionApp
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException


fun rotateRequired(bitmap: Bitmap, outputImage: File): Bitmap {
    val exif = ExifInterface(outputImage.path)
    val orientation =
        exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
    return when (orientation) {
        ExifInterface.ORIENTATION_ROTATE_90 -> rotateBitmap(bitmap, 90f)
        ExifInterface.ORIENTATION_ROTATE_180 -> rotateBitmap(bitmap, 180f)
        ExifInterface.ORIENTATION_ROTATE_270 -> rotateBitmap(bitmap, 270f)
        else -> bitmap
    }
}

fun rotateBitmap(bitmap: Bitmap, degree: Float): Bitmap {
    val matrix = Matrix()
    matrix.postRotate(degree)
    val rotatedBitmap =
        Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
    bitmap.recycle()
    return rotatedBitmap
}

//创建文件，并返回文件路径
fun getImage(strFileName: String): String {
    val strPath: String = DikeLeakageDetectionApp.context.getExternalFilesDir(null).toString()+"/saving_picture"
    val destDir = File(strPath)
    if (!destDir.exists()) {
        destDir.mkdirs()
    }
    val imageFileUri = "${strPath}/${strFileName}.jpg"
    val imageFile = File(imageFileUri)
    imageFile.createNewFile()
    return imageFileUri
}

fun saveImage(tempBitmap:Bitmap, imageFile: String) {
    try {
        val fos = FileOutputStream(File(imageFile))
        tempBitmap.compress(CompressFormat.JPEG, 50, fos)
        fos.flush()
        fos.close()
    } catch (e: FileNotFoundException) {
        e.printStackTrace()
    } catch (e: IOException) {
        e.printStackTrace()
    }
}

fun getImageByFilePath(filePath: String): Bitmap{
    val imageFile = File(filePath)
    val imageFileUri = Uri.fromFile(imageFile)
    return BitmapFactory.decodeStream(DikeLeakageDetectionApp.context.contentResolver.openInputStream(imageFileUri))
}